package cn.jbolt.core.enjoy.directive;

import cn.jbolt.core.util.JBoltFileSizeUtil;
import com.jfinal.template.Directive;
import com.jfinal.template.Env;
import com.jfinal.template.expr.ast.Expr;
import com.jfinal.template.expr.ast.ExprList;
import com.jfinal.template.io.Writer;
import com.jfinal.template.stat.ParseException;
import com.jfinal.template.stat.Scope;

/**
 * 文件大小格式化输出指令
 * @ClassName: FileSizeFormatterDirective
 * @author: JFinal学院-小木 QQ：909854136
 * @date: 2019年10月8日
 */
public class FileSizeFormatterDirective extends Directive {

	private Expr valueExpr;
	private int paraNum;

	@Override
	public void setExprList(ExprList exprList) {
		this.paraNum = exprList.length();
		if (paraNum == 0) {
			throw new ParseException("Wrong number parameter of #fileSizeFormatter directive, only one parameter", location);
		} else if (paraNum == 1) {
			this.valueExpr = exprList.getExpr(0);
		} else {
			throw new ParseException("Wrong number parameter of #fileSizeFormatter directive, only one parameter",
					location);
		}
	}

	@Override
	public void exec(Env env, Scope scope, Writer writer) {
		if (paraNum == 0) {
			write(writer, "0 B");
		} else {
			outputValue(env, scope, writer);
		}
	}

	/**
	 * 输出处理后的value值
	 *
	 * @param env
	 * @param scope
	 * @param writer
	 */
	private void outputValue(Env env, Scope scope, Writer writer) {
		Object value = this.valueExpr.eval(scope);
		if (value != null && value.toString().length() > 0) {
			Long fileSize = Long.valueOf(value.toString());
			write(writer, JBoltFileSizeUtil.format(fileSize));
		}
	}

}
